<?php
/**
 * Nordic Repository
 * 
 * LICENSE
 * 
 * The new BSD license is applied on this source-file. For further
 * information please visit http://license.nordic-dev.de/newbsd.txt
 * or send an email to andre.moelle@gmail.com.
 */

/**
 * Necessary includes.
 */
Zend_Loader::loadClass('Zend_Locale');

/**
 * Default adapter.
 * 
 * @category   Nordic
 * @package    Nordic_I18n
 * @copyright  2007 Nordic Development
 * @license    http://license.nordic-dev.de/newbsd.txt (New-BSD license)
 * @author     Andre Moelle <andre.moelle@gmail.com>
 * @version    $Id: Adapter.php 3 2007-07-08 09:21:42Z andre.moelle $
 */
class Nordic_I18n_Adapter implements Nordic_I18n_Adaptable
{
	/**
	 * Default language if no other is possible or was chosen.
	 * 
	 * @var string
	 */
	protected $_default;
	
	/**
	 * Actually chosen language.
	 * 
	 * @var string
	 */
	protected $_language;
	
	/**
	 * Possible languages.
	 * 
	 * @var array
	 */
	protected $_languages;
	
	/**
	 * Constructor.
	 * 
	 * Makes the object ready. If no language was given, Zend_Locale
	 * is used to determine the prefered language. If that language
	 * is invalid, the default-language is taken instead.
	 * 
	 * @param array $languages allowed languages
	 * @param string $default default-language
	 * @param string $lang optional set language
	 * @return void
	 */
	public function __construct ($languages, $default, $lang = null)
	{
		$this->_languages = $languages;
		$this->_default = $this->_prepare($default);
		
		if($lang != null)
		{
			$this->setLanguage($lang);
			return;
		}
		
		try
		{
			$locale = new Zend_Locale();
			$this->setLanguage($locale->getLanguage());
		}
		catch (Nordic_I18n_Exception $e)
		{
			$this->setLanguage($this->_default);
		}
	}
	
	/**
	 * Prepares the language.
	 * 
	 * The language string is lowered and possibly splitted using
	 * a separator like "_" or "-".
	 * 
	 * @param string $language language to prepare
	 * @return string
	 */
	protected function _prepare ($language)
	{
		$language = strtolower($language);
		
		foreach(array('_', '-') as $sep)
		{
			if(strpos($language, $sep) !== false)
			{
				list($language, $temp) = explode($sep, $language);
				break;
			}
		}
		
		return $language;
	}
	
	/**
	 * @see Nordic_I18n_Adaptable::getLanguage()
	 */
	public function getLanguage ()
	{
		return $this->_language;
	}
	
	/**
	 * @see Nordic_I18n_Adaptable::getLanguages()
	 */
	public function getLanguages ()
	{
		return $this->_languages;
	}
	
	/**
	 * @see Nordic_I18n_Adaptable::isValid()
	 */
	public function isValid ($language)
	{
		return (in_array($this->_prepare($language), $this->getLanguages()));
	}
	
	/**
	 * @see Nordic_I18n_Adaptable::setLanguage()
	 */
	public function setLanguage ($language)
	{
		$language = $this->_prepare($language);
		
		if(!$this->isValid($language) && $language != $this->_default)
		{
			throw new Nordic_I18n_Exception('Language "' . $language . '" is invalid');
		}
		
		$this->_language = $language;
	}
}
?>